﻿using log4net.Core;
using PLCCommunication.PLCType.Omron;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    public class PLCWrapper
    {
        private OmronFinsNet _plc;
        public bool _plcIsConnected;
        private readonly MqttTopicLogger _mqttTopicLogger = MqttTopicLogger.Instance;
        private readonly string _ipAddress;
        private readonly int _port;
        private readonly int _maxReconnectAttempts;
        private readonly int _reconnectDelay;
        public PLCDataReader _dataReader;
        public PLCWrapper(string ipAddress, int port, int maxReconnectAttempts = 3, int reconnectDelay = 5000)
        {
            _ipAddress = ipAddress;
            _port = port;
            _maxReconnectAttempts = maxReconnectAttempts;
            _reconnectDelay = reconnectDelay;
        }

        public async Task<bool> ConnectAsync()
        {
            try
            {
                _plc = new OmronFinsNet
                {
                    IpAddress = _ipAddress,
                    Port = _port
                };
                var connectResult = await Task.Run(() => _plc.ConnectServer());
                _plcIsConnected = connectResult.IsSuccess;
                if (_plcIsConnected)
                {
                    _dataReader = new PLCDataReader(GetPLCClient());
                    _mqttTopicLogger.WriteServiceStatus("PLC连接", "成功", "PLC连接成功");
                }
                else
                {
                    _mqttTopicLogger.WriteServiceStatus("PLC连接", "失败", "PLC连接失败");
                }
                return _plcIsConnected;
            }
            catch (Exception ex)
            {
                _mqttTopicLogger.WriteSystemError($"PLC连接失败: {ex.Message}", ex);
                return false;
            }
        }

        public void Disconnect()
        {
            if (_plcIsConnected)
            {
                _plc.ConnectClose();
                _plcIsConnected = false;
                _mqttTopicLogger.WriteServiceStatus("PLC连接", "断开", "与PLC断开连接");
            }
        }

        public OmronFinsNet GetPLCClient()
        {
            if (!_plcIsConnected || _plc == null)
            {
                throw new InvalidOperationException("PLC 未连接或未初始化。请先调用 ConnectAsync()。");
            }
            return _plc;
        }

        public async Task<bool> ReconnectAsync()
        {
            if (_plcIsConnected)
            {
                _mqttTopicLogger.WriteServiceStatus("PLC重连", "跳过", "PLC已连接，无需重连");
                return true;
            }

            for (int attempt = 1; attempt <= _maxReconnectAttempts; attempt++)
            {
                _mqttTopicLogger.WriteServiceStatus("PLC重连", "尝试", $"尝试重新连接PLC，第 {attempt} 次尝试");
                if (await ConnectAsync())
                {
                    _mqttTopicLogger.WriteServiceStatus("PLC重连", "成功", "PLC重新连接成功");
                    return true;
                }

                if (attempt < _maxReconnectAttempts)
                {
                    await Task.Delay(_reconnectDelay);
                }
            }

            _mqttTopicLogger.WriteSystemError($"PLC重新连接失败，已尝试 {_maxReconnectAttempts} 次");
            return false;
        }

        /// <summary>
        /// PLC连接状态属性
        /// </summary>
        public bool IsConnected => _plcIsConnected;
    }
}